package com.citywy.dao.impl;

import com.citywy.dao.AccountDao;
import com.citywy.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import javax.sql.DataSource;
import java.util.List;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{
    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Account findAccountById(int id) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),1);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    /**
     * 根据名称查询
     * @param name
     * @return
     */
    @Override
    public Account findAccountByName(String name) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),name);
        if(accounts.isEmpty()){
            return null;
        }
        if(accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    /**
     * 修改Account信息
     * @param account
     */
    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }

}
